package service;

import beans.User;
import beans.Warehouse;
import dbutils.DBHelper;
import utils.ValidationUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import static dbutils.DBHelper.*;

public class ProducerService {

    // 检查用户名是否存在
    public static boolean isUsernameExists(String username) {
        Connection conn = DBHelper.getConn();
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            String checkNameSql = "SELECT * FROM producer WHERE pname = ?";
            stat = conn.prepareStatement(checkNameSql);
            stat.setString(1, username);
            rs = stat.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        return false;
    }

    // 检查手机号是否存在
    public static boolean isPhoneExists(String phone) {
        Connection conn = DBHelper.getConn();
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            String checkPhoneSql = "SELECT * FROM producer WHERE pphone = ?";
            stat = conn.prepareStatement(checkPhoneSql);
            stat.setString(1, phone);
            rs = stat.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        return false;
    }

    /*
     * 插入空账号，用于注册
     */
    public void createNewCustomer(User producer) {
        Connection conn = DBHelper.getConn();
        String sql = "INSERT producer (pname,pphone,ppassword) VALUE(?,?,?);";
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, producer.getName());
            stat.setString(2, producer.getPhone());
            stat.setString(3, producer.getPassword());
            stat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBHelper.closeAll(conn,stat,rs);
        }
    }

//

    /*
     * 注册功能
     */
    public void signIn(String name,String phone, String password, String confirmPassword) {
        User producer = new User();
        String producerName = name;
        String producerPhone = phone;
        String customerPassword = ValidationUtil.getPassword(password, confirmPassword);
        producer.setName(producerName);
        producer.setPhone(producerPhone);
        producer.setPassword(customerPassword);
        producer.setMoney(0);
        //新建用户
        createNewCustomer(producer);

        // 更新用户到数据库
        updateProducer(producer);

        JOptionPane.showMessageDialog(null, "用户：" + producerName + " 注册完成！感谢使用本银行账户。");

        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        String dateTimeNow = sdf.format(time);
        LogService.addLogs(producer, "生产商 "+producerName + " 于" + dateTimeNow + "注册系统。");
    }

    //用户名登录
    public User loginN(String name,String password){
        User producer = findPname(name);
        // 判断账户是否存在，密码是否匹配
        if (producer != null && producer.getPassword().equals(password)) {
            // 登录成功
            JOptionPane.showMessageDialog(null,"登录成功！当前账号为：" + name);
            // 记录登录日志
            LogService.addLogs(producer, "生产商 " + producer.getName() + "登录系统");
            return producer;
        } else {
            // 登录失败，密码错误
            JOptionPane.showMessageDialog(null,"账号或密码错误，请重新输入");
            return null;
        }
    }

    //手机号登录
    public User loginP(String phone,String password){
        User producer = findPphone(phone);
        // 判断账户是否存在，密码是否匹配
        if (producer != null && producer.getPassword().equals(password)) {
            // 登录成功
            JOptionPane.showMessageDialog(null,"登录成功！当前用户为：" + producer.getName());
            // 记录登录日志
            LogService.addLogs(producer, "生产商 " + producer.getName() + "登录系统");
            return producer;
        } else {
            // 登录失败，密码错误
            JOptionPane.showMessageDialog(null,"账号或密码错误，请重新输入");
            return null;
        }
    }



    /*
     * 根据name查找数据库的账号
     * @param name
     * @return 返回对应name的 producer 对象，如果不存在返回null
     */
    public User findPname(String pname) {
        if (pname == null) {
            return null;
        }
        Connection conn = DBHelper.getConn();
        String sql = "select * from producer WHERE pname = ? ; ";
        PreparedStatement stat = null;
        ResultSet rs = null;
        User producer = new User();
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, pname);
            rs = stat.executeQuery();//executeQuery 该方法用来执行查询语句
            while (rs.next()) {
                producer.setId(rs.getInt("pid"));
                producer.setName(rs.getString("pname"));
                producer.setPhone(rs.getString("pphone"));
                producer.setPassword(rs.getString("ppassword"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        if (producer.getId() == 0) {
            return null;
        } else {
            return producer;
        }
    }

    /*
     * 根据phone查找数据库的账号
     * @param phone
     * @return 返回对应phone的 producer 对象，如果不存在返回null
     */
    public User findPphone(String cname) {
        if (cname == null) {
            return null;
        }
        Connection conn = DBHelper.getConn();
        String sql = "select * from producer WHERE pphone = ? ; ";
        PreparedStatement stat = null;
        ResultSet rs = null;
        User producer = new User();
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, cname);
            rs = stat.executeQuery();//executeQuery 该方法用来执行查询语句
            while (rs.next()) {
                producer.setId(rs.getInt("pid"));
                producer.setName(rs.getString("pname"));
                producer.setPhone(rs.getString("pphone"));
                producer.setPassword(rs.getString("ppassword"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        if (producer.getId() == 0) {
            return null;
        } else {
            return producer;
        }
    }


    /*
     * 更新指定producer的所有数据
     * @param producer 已设定好数据的 producer 对象
     */
    public void updateProducer(User producer) {
        Connection conn = DBHelper.getConn();
        String sql = "UPDATE producer SET pname = ?,pphone = ?,ppassword = ? WHERE pid = ?";
        PreparedStatement stat = null;
        ResultSet rs = null;

        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, producer.getName());
            stat.setString(2, producer.getPassword());
            stat.setString(3, producer.getPhone());
            stat.setInt(4, producer.getId());
            stat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
    }




    // 修改密码
    public void updatePassword(User producer, String oldPassword, String newPassword) {
        // 首先进行参数有效性检查
        if (newPassword.isEmpty()) {
            JOptionPane.showMessageDialog(null, "新密码不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (oldPassword.equals(newPassword)) {
            JOptionPane.showMessageDialog(null, "新密码不能和旧密码相同！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM producer WHERE pid = ? AND ppassword = ?";
        PreparedStatement selectStat = null;
        String updateSql = "UPDATE producer SET ppassword = ? WHERE pid = ?";
        PreparedStatement updateStat = null;

        try {
            // 验证旧密码是否正确
            selectStat = conn.prepareStatement(sql);
            selectStat.setInt(1, producer.getId());
            selectStat.setString(2, oldPassword);
            ResultSet resultSet = selectStat.executeQuery();

            if (resultSet.next()) {
                // 更新密码
                updateStat = conn.prepareStatement(updateSql);
                updateStat.setString(1, newPassword);
                updateStat.setInt(2, producer.getId());
                int rowsAffected = updateStat.executeUpdate();

                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(null, "密码修改成功！");
                    LogService.addLogs(producer, "生产商 " + producer.getName() + "修改密码成功");

                } else {
                    JOptionPane.showMessageDialog(null, "密码修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "旧密码错误！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, null);
            DBHelper.closeAll(conn, updateStat, null);
        }
    }


    // 商品展示
    public JTable createJTable(User producer) {
        // 创建表头
        String[] columnNames = {"ID", "商品", "数量", "价格", "尺码", "商家", "生产商"};

        // 创建 JTable 对象
        JTable table = new JTable();

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM warehouse WHERE wproducer=?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;
        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, producer.getName());
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("wid");
                String name = resultSet.getString("wname");
                int quantity = resultSet.getInt("wcount");
                double price = resultSet.getDouble("wprice");
                String size = resultSet.getString("wsize");
                String merchant = resultSet.getString("wmerchant");
                String wproducer = resultSet.getString("wproducer");

                // 添加数据行
                Object[] rowData = {id, name, quantity, price, size, merchant, wproducer};
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }

        return table;
    }



    // 修改商品价格
    public void performModifyPrice(JTable table,User producer) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int id = (int) table.getValueAt(selectedRow, table.getColumn("ID").getModelIndex());

        // 显示输入对话框，获取新的商品价格
        double newPrice;

        String inputPrice = JOptionPane.showInputDialog(null, "请输入新的价格：", "修改商品价格", JOptionPane.PLAIN_MESSAGE);
        if (inputPrice == null) {
            return; // 用户点击了取消按钮
        } else {
            try {
                newPrice = Double.parseDouble(inputPrice);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "请输入有效的价格！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setValueAt(newPrice, selectedRow, table.getColumn("价格").getModelIndex());

        // 更新数据库中的商品价格
        updateProductPriceInDatabase(id, newPrice);
        String name = (String) table.getValueAt(selectedRow, table.getColumn("商品").getModelIndex());
        LogService.addLogs(producer, "生产商 " + producer.getName() + "修改了商品 " + name + " 的价格");

    }


    // 更新商品价格到数据库
    public void updateProductPriceInDatabase(int id, double newPrice) {
        // 获取数据库连接
        Connection conn = DBHelper.getConn();
        PreparedStatement stmt = null;

        try {

            // 创建预处理语句
            String sql = "UPDATE warehouse SET wprice=? WHERE wid=?";
            stmt = conn.prepareStatement(sql);
            stmt.setDouble(1, newPrice);
            stmt.setInt(2, id);

            // 执行更新操作
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接和语句对象
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



    // 补货
    public void performReplenishProduct(JTable table, User producer) {
        int selectedRow = table.getSelectedRow();

        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择要补货的商品！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String name = (String) table.getValueAt(selectedRow, table.getColumn("商品").getModelIndex());

        // 输入补货数量
        int replenishQuantity = 50;

        String inputReplenishQuantity = JOptionPane.showInputDialog(null, "请输入补货数量（默认为输入50）：", "补货商品", JOptionPane.PLAIN_MESSAGE);
        if (inputReplenishQuantity == null) {
            return; // 用户点击了取消按钮
        } else {
            try {
                int inputQuantity = Integer.parseInt(inputReplenishQuantity);
                if (inputQuantity > 0) {
                    replenishQuantity = inputQuantity;
                } else {
                    JOptionPane.showMessageDialog(null, "补货数量必须大于0！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "请输入有效的补货数量！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        int count = (int) table.getValueAt(selectedRow, table.getColumn("数量").getModelIndex());

        int newcount = replenishQuantity + count;
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setValueAt(newcount, selectedRow, table.getColumn("数量").getModelIndex());
        // 更新仓库库存数量
        updateWarehouseCountForReplenish(name, newcount);

        JOptionPane.showMessageDialog(null, "补货成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        LogService.addLogs(producer,"生产商 " + producer.getName() + " 补货 " + name + " " + count + " 件");
    }





    // 更新仓库库存数量
    public void updateWarehouseCountForReplenish(String name, int replenishQuantity) {
        // 获取数据库连接
        Connection conn = DBHelper.getConn();
        PreparedStatement stmt = null;

        try {
            // 创建预处理语句
            String sql = "UPDATE warehouse SET wcount = ? WHERE wname=?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, replenishQuantity);
            stmt.setString(2, name);

            // 执行更新操作
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接和语句对象
            try {
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    //查询商品
    public void searchTable(JTable table, String keyword) {
        // 清空表格数据
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM warehouse WHERE wname LIKE ?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, "%" + keyword + "%");
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                Object[] rowData = new Object[7];
                rowData[0] = resultSet.getInt("wid");
                rowData[1] = resultSet.getString("wname");
                rowData[2] = resultSet.getInt("wcount");
                rowData[3] = resultSet.getDouble("wprice");
                rowData[4] = resultSet.getString("wsize");
                rowData[5] = resultSet.getString("wmerchant");
                rowData[6] = resultSet.getString("wproducer");

                // 添加数据行
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }
    }



    //刷新仓库
    public void refreshWareData(JTable table, User producer) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);  // 清空表格

        try (Connection conn = DriverManager.getConnection(URL, DBUser, DBPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM warehouse where wproducer = '" + producer.getName() + "';")) {

            while (rs.next()) {
                Object[] rowData = new Object[7];
                rowData[0] = rs.getInt("wid");
                rowData[1] = rs.getString("wname");
                rowData[2] = rs.getInt("wcount");
                rowData[3] = rs.getDouble("wprice");
                rowData[4] = rs.getString("wsize");
                rowData[5] = rs.getString("wmerchant");
                rowData[6] = rs.getString("wproducer");

                model.addRow(rowData);
            }

            // 刷新表格
            model.fireTableDataChanged();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }



    // 查询订单（只显示带有补货状态的订单）
    public void showOrderData(JTable table, User producer) {
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);

        try {
            Connection conn = DBHelper.getConn();
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM corders WHERE producer LIKE ?;");
            ps.setString(1, "%" + producer.getName() + "%"); // 使用LIKE和通配符进行模糊匹配

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                String producerName = rs.getString("producer");

                if (!producerName.contains("(未补货)") && !producerName.contains("(已补货)")) {
                    continue; // 如果商家名不包含补货状态，则跳过该记录
                }

                Object[] rowData = new Object[7];
                rowData[0] = rs.getString("orderNum");
                rowData[1] = rs.getString("user");
                rowData[2] = rs.getString("times");
                rowData[3] = rs.getString("name");
                rowData[4] = rs.getString("price");
                rowData[5] = rs.getString("merchant");
                rowData[6] = rs.getString("producer");

                tableModel.addRow(rowData);
            }

            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //补货状态切换
    public void updateReplenishmentStatus(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 获取选中行的订单编号和生产商名称
        String orderNum = (String) table.getValueAt(selectedRow, table.getColumn("订单编号").getModelIndex());
        String producerName = (String) table.getValueAt(selectedRow, table.getColumn("生产商").getModelIndex());

        // 判断生产商名称是否包含补货状态标识
        if (!producerName.contains("(未补货)") && !producerName.contains("(已补货)")) {
            return; // 如果商家名不包含补货状态，则退出方法
        }

        boolean isReplenished = producerName.contains("(未补货)"); // 判断当前状态，用于更新状态值

        // 更新表格中的生产商列
        String newProducer = isReplenished ? producerName.replace("(未补货)", "(已补货)") : producerName.replace("(已补货)", "(未补货)");
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setValueAt(newProducer, selectedRow, table.getColumn("生产商").getModelIndex());

        try {
            // 更新数据库中的生产商
            Connection conn = DBHelper.getConn();
            PreparedStatement ps = conn.prepareStatement("UPDATE corders SET producer=? WHERE orderNum=?");
            ps.setString(1, newProducer);
            ps.setString(2, orderNum);

            int rowsAffected = ps.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "补货状态切换成功！！");
            } else {
                JOptionPane.showMessageDialog(null, "补货失败！！！");
            }

            ps.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }




    // 更新表格显示的订单数据
    public JTable refreshOrderData(JTable table, User producer) {
        // 创建表头
        String[] columnNames = {"订单编号", "用户", "下单时间", "商品", "商品价格", "商家", "生产商" };

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM corders WHERE producer LIKE ?";
        PreparedStatement selectStat = null;
        ResultSet rs = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, "%" + producer.getName() + "%");

            rs = selectStat.executeQuery();

            while (rs.next()) {
                String producerName = rs.getString("producer");

                if (!producerName.contains("(未补货)") && !producerName.contains("(已补货)"))
                    continue; // 如果商家名不包含补货状态，则跳过该记录

                Object[] rowData = new Object[7];
                rowData[0] = rs.getString("orderNum");
                rowData[1] = rs.getString("user");
                rowData[2] = rs.getString("times");
                rowData[3] = rs.getString("name");
                rowData[4] = rs.getString("price");
                rowData[5] = rs.getString("merchant");
                rowData[6] = rs.getString("producer");

                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, rs);
        }

        return table;
    }






    public void performReplenishProduct2(JTable table, User producer) {
        int selectedRow = table.getSelectedRow();

        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择要补货的商品！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String merchantName = (String) table.getValueAt(selectedRow, table.getColumn("商家名").getModelIndex());
        if (!merchantName.endsWith("(未补货)")) {
            JOptionPane.showMessageDialog(null, "该商品已经补过货了，请重新选择！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String productName = (String) table.getValueAt(selectedRow, table.getColumn("商品名").getModelIndex());

        // 弹出一个对话框，让用户输入补货数量
        String input = JOptionPane.showInputDialog(null, "请输入补货数量：", 1);
        if (input == null) {
            return; // 如果用户点击了取消，则不进行补货
        }

        int replenishQuantity;
        try {
            replenishQuantity = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "请输入一个有效的数字！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 更新数据库中的补货状态和数量
        updateProductReplenishStatusAndQuantity(productName, producer.getName(), replenishQuantity);

        // 更新表格中商家名称和日志
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        String newMerchantName = merchantName.substring(0, merchantName.length() - 5) + "(已补货)";
        model.setValueAt(newMerchantName, selectedRow, table.getColumn("商家名").getModelIndex());

        // 将更新后的状态更新到数据库
        updateDatabaseWithReplenishStatus(productName, producer.getName(), newMerchantName);

        JOptionPane.showMessageDialog(null, "补货成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        LogService.addLogs(producer, "生产商 " + producer.getName() + " 补货 " + productName + " " + replenishQuantity + " 件");
    }

    //更新补货状态和数量
    private void updateProductReplenishStatusAndQuantity(String productName, String producerName, int replenishQuantity) {
        try {
            Connection conn = DBHelper.getConn();
            PreparedStatement ps = conn.prepareStatement("UPDATE warehouse SET wcount = ?, wproducer = ? WHERE wname = ?;");
            ps.setInt(1, replenishQuantity);
            ps.setString(2, producerName);
            ps.setString(3, productName);
            ps.executeUpdate();

            ps.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }


    // 将更新后的状态更新到数据库
    private void updateDatabaseWithReplenishStatus(String productName, String producerName, String newMerchantName) {
        try {
            Connection conn = DBHelper.getConn();
            PreparedStatement ps = conn.prepareStatement("UPDATE warehouse SET wmerchant = ? WHERE wname = ? AND wproducer = ?;");
            ps.setString(1, newMerchantName);
            ps.setString(2, productName);
            ps.setString(3, producerName);
            ps.executeUpdate();

            ps.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }









    //查询日志
    public void showLogData(JTable table, User producer) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);  // 清空表格

        try (Connection conn = DriverManager.getConnection(URL, DBUser, DBPassword);
             PreparedStatement ps = conn.prepareStatement("SELECT * FROM logs WHERE userName = ?");
        ) {

            ps.setString(1, producer.getName());

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = new Object[3];
                    rowData[0] = rs.getString("userName");
                    rowData[1] = rs.getString("times");
                    rowData[2] = rs.getString("logContext");

                    model.addRow(rowData);
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }


    // 刷新日志
    public JTable refreshLogData(JTable table, User producer) {
        // 创建表头
        String[] columnNames = {"用户名", "时间", "日志内容"};

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM logs where userName = ?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, producer.getName());
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                Object[] rowData = new Object[3];
                rowData[0] = resultSet.getString("userName");
                rowData[1] = resultSet.getString("times");
                rowData[2] = resultSet.getString("logContext");

                // 添加数据行
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }

        return table;
    }







    /*
     * 登出功能
     */
    public void Logout(User user_Login) {
        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        String dataTimeNow = sdf.format(time);
        //记录登出系统时间
        LogService.addLogs(user_Login, user_Login.getName() + " 于" + dataTimeNow + "  登出系统。");
        JOptionPane.showMessageDialog(null, user_Login.getName() + " 生产商于" + dataTimeNow + "  登出系统。");
        //将当前登出清除
        user_Login = null;
    }
}
